# coding=utf-8
from bs4 import BeautifulSoup
import XMLParser as XP
import os
import shutil
import os.path
import re
                
def joinHead(soup):
    fetchHeadContent(soup)

def filterHeadCondition(tag):  
    shouldSelect = (tag.name == 'style')
    return shouldSelect

def fetchBodyContent(soup, tagAttributePair):
    tag = soup.find(attrs=tagAttributePair)
    return tag

def fetchHeadContent(soup):
    head = soup.head
    tags = head.find_all(filterHeadCondition)
    return tags

def correctIndexTagName(tag, tagAttributePair, correctName):
    targets = tag.find_all(attrs=tagAttributePair)
    for target in targets:
        target.name = correctName
    return tag

def correctImageSrcPath(tag, key_list):
    nodes = tag.find_all('img')
    for node in nodes:
        for key in key_list:
            src_value = node[key]
            src_value_tokens = src_value.split('/')
            file_name = src_value_tokens[-1]
            src_value_change_to = os.curdir + '/images/' + file_name
            node[key] = src_value_change_to
    return tag


def removeCondition(tag):
    if tag.has_attr('class'):
        atti_class_list = tag['class']
        for attri_value in atti_class_list:
            if ('annotator-modal-wrapper' in attri_value):
                return True
    return False

def removeUselessModule(tag, attri):
    nodes = tag.find_all('div')
    for node in nodes:
        tags = node.find_all(removeCondition)
        for each_tag in tags:
            each_tag.extract()
    return tag


def wrapTag(soup, tag, wrapTagName, attributeMap):
    tag = tag.wrap(soup.new_tag(wrapTagName))
    for key in attributeMap.keys():
        tag[key] = attributeMap[key]
    return tag

def parseSourceStreamFromFile(file_path = '', bookName = 'test'):
    try:
        file_object = open(file_path, encoding='utf-8')
        all_the_text = file_object.read()
        return parseSourceStream(all_the_text, bookName)
    finally:
        file_object.close()

def parseSourceStream(response = '', bookName = 'test'):
    try:
        # New a tree from template
        tree = XP.read_xml('template.html')

        # Read page source from the web page
        soup = BeautifulSoup(response, 'lxml')
       
        # We acctually should use the following code. Currently we have not yet got the stream, so keep it.
        # soup = BeautifulSoup(response, 'lxml')

        # Get Chapter Title
        h1title = soup.h1
        tag = h1title.find(attrs = {'class':'visuallyhidden'})
        tag.extract()
        h1title.name = 'p'
        h1title['class'] = 'title'

        titleElement = soup.title
        contentTitle = titleElement.text
        contentTitle = re.sub('[:\\\\/|?<>*"]', '', contentTitle)
        tokens = contentTitle.split('-')
        contentTitle = tokens[0]
        contentTitle.rstrip()
        # Deal with body content.
        body = fetchBodyContent(soup, {'id':'sbo-rt-content'})

        # In order to add index into pdf files, we have to construct the tree level in content.
        body = correctIndexTagName(body, {'class', 'ChapterTitle'}, 'h2')
        body = correctIndexTagName(body, {'class', 'Heading1'}, 'h3')

        body = correctImageSrcPath(body, ['data-mfp-src', 'src'])
        
        body = removeUselessModule(body, {'class':'annotator-modal-wrapper'})

        bodyStr = str(body)
        titleStr = str(h1title)
        # XML Path to arrange the new tree
        # Head: Currently we decide to use static template.

        # Body
        bodyNode = XP.readFromString(bodyStr)
        titleNode = XP.readFromString(titleStr)
        node = bodyNode.find('div')
        node.insert(0, titleNode)

        node = tree.find('body')
        node.set('class', 'reading sidenav  scalefonts library nav-collapsed')
        node.append(bodyNode)

        # Copy Resources
        dirPath = '.\\' + bookName
        htmlFileName = contentTitle + '.html'
        # Write File
        if not os.path.exists(dirPath):
            os.makedirs(dirPath)
        outName = dirPath + os.sep + htmlFileName
        XP.write_xml(tree, outName, False)

    finally:
        return contentTitle

def copyResource(book_name):
    dir_path = os.curdir + os.sep + book_name
    static_dir_name = 'static'
    images_dir_name = 'images'
    static_src_dir = os.curdir + os.sep + static_dir_name #'./static'
    images_src_dir = os.curdir + os.sep + images_dir_name #'./images'

    static_dest_dir = dir_path+ os.sep + static_dir_name
    images_dest_dir = dir_path + os.sep + images_dir_name
    if not os.path.exists(dir_path + os.sep + 'static'):
        shutil.copytree(static_src_dir, static_dest_dir)
    if not os.path.exists(dir_path + os.sep + 'images'):
        shutil.copytree(images_src_dir, images_dest_dir)